package com.example.esp32;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.espressif.iot.esptouch2.provision.EspProvisioner;
import com.espressif.iot.esptouch2.provision.EspProvisioningListener;
import com.espressif.iot.esptouch2.provision.EspProvisioningRequest;
import com.espressif.iot.esptouch2.provision.EspProvisioningResult;
import com.espressif.iot.esptouch2.provision.TouchNetUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class esppew extends AppCompatActivity {
    private Context mContext;
    private WifiManager mWifiManager;
    private String mBssid;

    private List<getValue> ddList = new ArrayList<getValue>();
    List<ScanResult> able;
    private ListView listView;
    private String pawer = null;
    private String cusdat = null;
    private String aske = null;
private LocationManager locationManager;
    adapterwifi adapter=new adapterwifi(esppew.this,ddList);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_esppew);
        listView=findViewById(R.id.esplists);

        //判断是否开启了GPS


        if (ContextCompat.checkSelfPermission(esppew.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(esppew.this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                Toast.makeText(esppew.this, "请同意权限并打开定位和WiFi",Toast.LENGTH_SHORT).show();
                ActivityCompat.requestPermissions(this,new String[]{ Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_BACKGROUND_LOCATION,Manifest.permission.WRITE_SETTINGS
                },10000);
            } else {
                ActivityCompat.requestPermissions(this,new String[]{ Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_BACKGROUND_LOCATION,Manifest.permission.WRITE_SETTINGS
            },10000);
            }}

         locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);




        mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

        SwipeRefreshLayout srl_my_refresh = findViewById(R.id.lisss);

        final Timer t = new Timer();
        t.schedule(new TimerTask() {
            public void run() {
//                Toast.makeText(esppew.this,""+ scanResults.get(0),Toast.LENGTH_SHORT).show();

            }
        }, 2000);
        //第二步，设置 下拉刷新时的颜色
        srl_my_refresh.setColorSchemeColors(Color.parseColor("#ff0000"),Color.parseColor("#00ff00"));
        //监听 刷新是回调
        srl_my_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                srl_my_refresh.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        srl_my_refresh.setRefreshing(false);

                        boolean ok = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

                        if(!ok)
                        {Toast.makeText(esppew.this,"请打开定位",Toast.LENGTH_LONG).show();
                            adapter.clear();}
                        else {
                            mWifiManager.startScan(); //启动扫描
                            if (ActivityCompat.checkSelfPermission(esppew.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                // TODO: Consider calling
                                //    ActivityCompat#requestPermissions
                                // here to request the missing permissions, and then overriding
                                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                //                                          int[] grantResults)
                                // to handle the case where the user grants the permission. See the documentation
                                // for ActivityCompat#requestPermissions for more details.
                                return;
                            }
                            List<ScanResult> scanResults = mWifiManager.getScanResults();//搜索到的设备列表
                            for (int i = 0; i < scanResults.size() - 1; i++) {
                                for (int j = 0; j < scanResults.size() - 1 - i; j++) {
                                    if (scanResults.get(j).level <= scanResults.get(j+1).level) {
                                        Collections.swap(scanResults,j,j+1);

                                    }
                                }

                            }
                            able=scanResults;
                            adapter.clear();
                            String ab="";
                            for(int i=0;i<scanResults.size();i++){
                                int xhqd=scanResults.get(i).level;
//                            wifi(scanResults.get(i).SSID,scanResults.get(i).BSSID, String.valueOf(scanResults.get(i).level));
//                            adapter.clear();
                                getValue dd = new getValue();
                                String a=String.valueOf(scanResults.get(i).level);
                                if(Math.abs(xhqd)>=85&Math.abs(xhqd)<=100){
                                    dd.setTupian(R.drawable.wifia);
                                } else if (Math.abs(xhqd)>=70&Math.abs(xhqd)<=85) {
                                    dd.setTupian(R.drawable.wifib);
                                }else if (Math.abs(xhqd)>=55&Math.abs(xhqd)<=70) {
                                    dd.setTupian(R.drawable.wific);
                                }else if (Math.abs(xhqd)>=0&Math.abs(xhqd)<=55) {
                                    dd.setTupian(R.drawable.wifid);
                                }else {                                dd.setTupian(R.drawable.wifid);
                                }
                                String b=scanResults.get(i).SSID;
                                String c=scanResults.get(i).capabilities;

                                if(c.equals("[ESS]")){
                                    ab="开放";
                                } else if (!c.equals("[ESS]")) {
                                    ab="加密";
                                }

                                dd.setsbmc(a );
                                dd.setas(b);
                                dd.setdyzt(ab);
                                ddList.add(dd);
                                System.out.println(scanResults.get(i));}
                            listView.setAdapter(adapter);
                        }


                    }
                },30);
            }

        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
String ssid=mWifiManager.getConnectionInfo().getSSID();
                if(ssid.equals("<unknown ssid>")){
                    Toast.makeText(esppew.this, "请先连接WiFi再广播", Toast.LENGTH_SHORT).show();

                }else {
                    byte[] ssdi = ((TextView) view.findViewById(R.id.ssid)).getText().toString().getBytes();
                String ssidd=String.valueOf(able.get(position).BSSID);
                byte[] password=pawer.getBytes();
                mBssid=ssidd;
                byte[] bssid=getBssidBytes();
                byte[] customData=cusdat.getBytes();
                byte[] aesKey= aske.getBytes();
                boolean olk=tck(((TextView) view.findViewById(R.id.ssid)).getText().toString());
                if(!olk){
                    wifi(ssdi,bssid,password,customData,aesKey);
                }



                    Toast.makeText(esppew.this, "第" + position + "个" + ssid, Toast.LENGTH_SHORT).show();
                }

            }

        });
        adapter.setOnItemxxxxClickListener(new adapterwifi.xxxx() {
            @Override
            public void onxxxxClick(int i) {


                LayoutInflater factory = LayoutInflater.from(esppew.this);

                final View DialogView = factory.inflate(R.layout.tckk, null);

                TextView SSID=DialogView.findViewById(R.id.SSID);
                SSID.setText(able.get(i).SSID);
                TextView BSSID=DialogView.findViewById(R.id.BSSID);
                BSSID.setText(String.valueOf(able.get(i).BSSID));
                TextView capabilities=DialogView.findViewById(R.id.capabilities);
                capabilities.setText(String.valueOf(able.get(i).capabilities));
                TextView level=DialogView.findViewById(R.id.level);
                level.setText(String.valueOf(able.get(i).level));
                TextView name=DialogView.findViewById(R.id.name);
                name.setText( String.valueOf(able.get(i).frequency));
//    AlertDialog.Builder builder=new AlertDialog.Builder(pew.this);
                AlertDialog dlg = new AlertDialog.Builder(esppew.this)
                        .setTitle("详细信息显示")
                        .setView(DialogView)//设置自定义对话框的样式

                        .create();//创建弹出框
                dlg.show();//显示
            }

        });

//        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(esppew.this,"chang",Toast.LENGTH_LONG).show();
//                return false;
//            }
//        });
    }
    private byte[] getBssidBytes() {
        return mBssid == null ? null : TouchNetUtil.convertBssid2Bytes(mBssid);
    }
    private void wifi(byte[] ssid, byte[] bssid, byte[] password, byte[] customData, byte[] aesKey) {
        EspProvisioner provisioner = new EspProvisioner(esppew.this);
        EspProvisioningRequest request = new EspProvisioningRequest.Builder(esppew.this)
                .setSSID(ssid) // AP's SSID,
                .setBSSID(bssid) // AP's MAC,
                .setPassword(password) // AP's password,
                .setReservedData(customData)
                .setAESKey(aesKey)
                .build();
        EspProvisioningListener listener = new EspProvisioningListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onResponse(EspProvisioningResult result) {

            }


            @Override
            public void onStop() {
            }

            @Override
            public void onError(Exception e) {
            }
        };
        provisioner.startProvisioning(request, listener); // request is nonnull, listener is nullable
    }

//    public void wifi(){
//
//    }
public void tk(String v){
//    edit_one = (EditText) findViewById(R.id.edit_one);



}
public boolean tck(String v){
//    edit_one = (EditText) findViewById(R.id.edit_one);
    final boolean[] a = {false};
    LayoutInflater factory = LayoutInflater.from(esppew.this);


    final View DialogView = factory.inflate(R.layout.exie, null);


//    AlertDialog.Builder builder=new AlertDialog.Builder(pew.this);
    AlertDialog dlg = new AlertDialog.Builder(esppew.this)
            .setTitle(v+"请输入密码")
            .setView(DialogView)//设置自定义对话框的样式
            .setPositiveButton("确定", //设置"确定"按钮
                    new DialogInterface.OnClickListener() //设置事件监听
                    {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            //输入后点击“确定”，开始获取我们要的内容 DialogView就是AlertDialog弹出的Activity
                            EditText edtUserName = (EditText)DialogView.findViewById(R.id.password);
                            String pawera = edtUserName.getText().toString();
                            EditText customData = (EditText)DialogView.findViewById(R.id.password);
                            String cusdata = customData.getText().toString();
                            EditText aesKey = (EditText)DialogView.findViewById(R.id.password);
                            String askey = aesKey.getText().toString();
                            if(!pawera.equals("")){
                                cusdat =cusdata;
                                pawer=pawera;
                                aske=askey;
                                a[0] =true;
                                Toast.makeText(esppew.this,"提交成功"+v+","+pawera,Toast.LENGTH_LONG).show();
                            }else {
                                Toast.makeText(esppew.this,"请输入密码",Toast.LENGTH_LONG).show();
                            }
                        }
                    })
            .create();//创建弹出框
    dlg.show();//显示

return a[0];


}
//public static boolean isLocServiceEnable(Context context) {
//    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//    boolean gps = locationManager.isProviderEnabled(LocationManager.ACCESS_FINE_LOCATION);
//    boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//    if (gps || network) {
//        return true;
//    }
//    return false;
//}



    }